<template>
  <div class="admin-layout">
    <!-- 顶部导航栏 -->
    <el-header class="header">
      <div class="header-left">
        <div class="logo">
          <span>智联物流 - 管理端</span>
        </div>
      </div>
      <div class="header-right">
        <el-dropdown trigger="click">
          <div class="user-info">
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :on-change="handleAvatarChange"
              accept="image/*"
            >
              <el-avatar
                :size="32"
                :src="avatarUrl"
                style="cursor:pointer"
              />
            </el-upload>
            <span class="username">{{ userStore.getUsername || '管理员' }}</span>
            <el-icon><CaretBottom /></el-icon>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="showProfileDialog">
                <el-icon><User /></el-icon>
                个人信息
              </el-dropdown-item>
              <el-dropdown-item>
                <el-icon><Setting /></el-icon>
                系统设置
              </el-dropdown-item>
              <el-dropdown-item divided @click="handleLogout">
                <el-icon><SwitchButton /></el-icon>
                退出登录
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </el-header>

    <div class="main-container">
      <!-- 左侧菜单 -->
      <el-aside :width="isCollapse ? '64px' : '220px'" class="aside">
        <div class="menu-header">
          <el-button
            type="text"
            class="collapse-btn"
            @click="toggleCollapse"
          >
            <el-icon>
              <component :is="isCollapse ? 'Expand' : 'Fold'" />
            </el-icon>
          </el-button>
        </div>
        <el-menu
          :default-active="activeMenu"
          class="menu"
          :collapse="isCollapse"
          :collapse-transition="false"
          router
        >
          <el-menu-item index="/admin/dashboard">
            <el-icon><DataLine /></el-icon>
            <template #title>数据概览</template>
          </el-menu-item>
     
          <!-- 仓库管理二级菜单 -->
          <el-sub-menu index="warehouse-management">
            <template #title>
              <el-icon><Box /></el-icon>
              <span>仓库管理</span>
            </template>

            <el-menu-item index="/admin/warehouse/inventory">
              <el-icon><List /></el-icon>
              <span>库存管理</span>
            </el-menu-item>

          </el-sub-menu>


          <el-menu-item index="/admin/users">
            <el-icon><User /></el-icon>
            <template #title>用户管理</template>
          </el-menu-item>


          <el-menu-item index="/admin/orders">
            <el-icon><List /></el-icon>
            <template #title>订单管理</template>
          </el-menu-item>


          <!-- 货物跟踪二级菜单 -->
          <el-sub-menu index="cargo-management">
            <template #title>
              <el-icon><Location /></el-icon>
              <span>货物跟踪</span>
            </template>

            <el-menu-item index="/admin/cargo/tracking">
              <el-icon><LocationInformation /></el-icon>
              <span>实时定位</span>
            </el-menu-item>

            <el-menu-item index="/admin/cargo/alerts">
              <el-icon><Warning /></el-icon>
              <span>异常预警</span>
            </el-menu-item>
          </el-sub-menu>

          <el-menu-item index="/admin/deliverymen">
            <el-icon><Van /></el-icon>
            <template #title>配送员管理</template>
          </el-menu-item>


        </el-menu>
      </el-aside>

      <!-- 主要内容区 -->
      <el-main class="main">
        <router-view v-slot="{ Component }">
          <transition name="fade" mode="out-in">
            <component :is="Component" />
          </transition>
        </router-view>
      </el-main>
    </div>

    <!-- 个人信息对话框 -->
    <el-dialog
      v-model="profileDialogVisible"
      title="个人信息"
      width="500px"
      :close-on-click-modal="false"
      class="profile-dialog"
    >
      <div class="profile-content">
        <!-- 头像区域 -->
        <div class="avatar-section">
          <el-upload
            class="profile-avatar-uploader"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :on-change="handleAvatarChange"
            accept="image/*"
          >
            <el-avatar
              :size="100"
              :src="avatarUrl"
              style="cursor:pointer"
            />
            <div class="upload-hint">点击更换头像</div>
          </el-upload>
        </div>

        <!-- 用户信息表单 -->
        <el-form
          :model="userProfile"
          label-width="100px"
          class="profile-form"
        >
          <el-form-item label="用户名">
            <el-input v-model="userProfile.username" disabled />
          </el-form-item>
          
          <el-form-item label="密码">
            <el-input v-model="userProfile.password" type="password" placeholder="请输入密码" />
          </el-form-item>
          
          <el-form-item label="手机号码">
            <el-input v-model="userProfile.phone" placeholder="请输入手机号码" />
          </el-form-item>
          
          <el-form-item label="昵称">
            <el-input v-model="userProfile.nickname" placeholder="请输入昵称" />
          </el-form-item>
          
          <el-form-item label="创建时间">
            <el-input v-model="userProfile.createAt" disabled placeholder="创建时间" />
          </el-form-item>

        </el-form>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="profileDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveProfile">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  CaretBottom,
  User,
  Setting,
  SwitchButton,
  Expand,
  Fold,
  DataLine,
  Van,
  List
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import {adminFindPage} from "@/assets/admin.js";
import {useUserStore} from "@/pinia/index.js";

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 菜单折叠状态
const isCollapse = ref(false)
const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value
}

// 当前激活的菜单
const activeMenu = computed(() => route.path)

// 头像上传与本地持久化
const defaultAvatar = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
const avatarUrl = ref(defaultAvatar)

onMounted(() => {
  const saved = localStorage.getItem('admin-avatar')
  if (saved) avatarUrl.value = saved
  
  // 加载用户信息
  loadUserProfile()
})

const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB!')
    return false
  }
  return true
}

const handleAvatarChange = (file) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    avatarUrl.value = e.target.result
    localStorage.setItem('admin-avatar', e.target.result)
  }
  reader.readAsDataURL(file.raw)
}

// 个人信息对话框
const profileDialogVisible = ref(false)

// 用户信息
const userProfile = ref({
  username: '',
  password: '',
  phone: '',
  nickname: '',
  createAt: '',
  position: '',
  joinDate: '',
  bio: ''
})

// 从后端获取用户信息
const loadUserProfile = async () => {
  try {
    // 从Pinia获取当前登录用户信息
    const currentUser = userStore.getUser
    if (!currentUser || !currentUser.username) {
      ElMessage.warning('未找到用户信息，请重新登录')
      return
    }
    
    const response = await adminFindPage({
      username: currentUser.username
    })
    
    if (response.data.code === 200) {
      const userInfo = response.data.data
      if (userInfo && userInfo.length > 0) {
        const user = userInfo[0] // 取第一个用户信息
        userProfile.value = {
          username: user.username || currentUser.username || '',
          password: user.password || currentUser.password || '',
          phone: user.phone || currentUser.phone || '',
          nickname: user.nickname || currentUser.nickname || '',
          createAt: user.createAt || user.createdAt || currentUser.createdAt || '',
          position: user.position || '',
          joinDate: user.joinDate || '',
          bio: user.bio || ''
        }
      } else {
        // 如果后端没有返回数据，使用Pinia中的用户信息
        userProfile.value = {
          username: currentUser.username || '',
          password: currentUser.password || '',
          phone: currentUser.phone || '',
          nickname: currentUser.nickname || '',
          createAt: currentUser.createdAt || '',
          position: '',
          joinDate: '',
          bio: ''
        }
      }
    } else {
      // 如果API调用失败，使用Pinia中的用户信息作为备选
      userProfile.value = {
        username: currentUser.username || '',
        password: currentUser.password || '',
        phone: currentUser.phone || '',
        nickname: currentUser.nickname || '',
        createAt: currentUser.createdAt || '',
        position: '',
        joinDate: '',
        bio: ''
      }
      console.warn('获取用户信息失败:', response.data.message)
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    // 出错时使用Pinia中的用户信息作为备选
    const currentUser = userStore.getUser
    if (currentUser) {
      userProfile.value = {
        username: currentUser.username || '',
        password: currentUser.password || '',
        phone: currentUser.phone || '',
        nickname: currentUser.nickname || '',
        createAt: currentUser.createdAt || '',
        position: '',
        joinDate: '',
        bio: ''
      }
    }
    // ElMessage.error('获取用户信息失败，请检查网络连接')
  }
}

// 保存用户信息
const saveProfile = async () => {
  try {
    // 这里可以调用更新用户信息的API
    // const response = await updateUserProfile(userProfile.value)
    
    // 暂时保存到localStorage
    localStorage.setItem('admin-profile', JSON.stringify(userProfile.value))
    ElMessage.success('个人信息保存成功！')
    profileDialogVisible.value = false
  } catch (error) {
    console.error('保存用户信息失败:', error)
    ElMessage.error('保存失败，请重试')
  }
}

// 显示个人信息对话框
const showProfileDialog = () => {
  profileDialogVisible.value = true
  // 每次打开对话框时重新加载最新数据
  loadUserProfile()
}

// 退出登录
const handleLogout = () => {
  // 清除用户信息
  userStore.setUser({})
  userStore.setId('')
  userStore.setUsername('')
  localStorage.removeItem('token')
  localStorage.removeItem('admin-avatar')
  localStorage.removeItem('admin-profile')
  ElMessage.success('退出登录成功')
  router.push('/login')
}
</script>

<style scoped>
.admin-layout {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f9fafb;
}

/* 顶部导航栏样式 */
.header {
  height: 90px;
  background: linear-gradient(135deg,
  rgba(22, 93, 255, 0.98) 0%,
  rgba(54, 124, 240, 0.96) 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 28px;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  box-shadow: 0 4px 30px rgba(0, 0, 0, 0.12);
  transition: all 0.4s cubic-bezier(0.25, 0.8, 0.25, 1);
  backdrop-filter: blur(10px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.12);
}

.header:before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 100%;
  background: linear-gradient(135deg,
  rgba(22, 93, 255, 0.2) 0%,
  rgba(54, 124, 240, 0.2) 100%);
  z-index: -1;
}

.header:hover {
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.16);
  background: linear-gradient(135deg,
  rgba(20, 84, 230, 0.98) 0%,
  rgba(51, 117, 230, 0.96) 100%);
  transform: translateY(-1px);
}

.logo {
  display: flex;
  align-items: center;
  gap: 14px;
  padding: 8px 16px;
  border-radius: 12px;
  background: rgba(255, 255, 255, 0.08);
  transition: all 0.4s ease;
  position: relative;
  overflow: hidden;
}

.logo::after {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: linear-gradient(
      to bottom right,
      rgba(255, 255, 255, 0) 0%,
      rgba(255, 255, 255, 0.1) 50%,
      rgba(255, 255, 255, 0) 100%
  );
  transform: rotate(30deg);
  transition: all 0.6s ease;
}

.logo:hover {
  background: rgba(255, 255, 255, 0.12);
  transform: translateY(-2px);
}

.logo:hover::after {
  left: 100%;
  top: 100%;
}
.logo span {
  font-size: 30px;
  font-weight: 600;
  letter-spacing: 0.5px;
  background: linear-gradient(90deg,
  #ffffff,
  rgba(224, 234, 255, 0.9));
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  position: relative;
  z-index: 1;
}

.user-info {
  color: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 18px;
  border-radius: 12px;
  transition: all 0.4s cubic-bezier(0.25, 0.8, 0.25, 1);
  background: rgba(255, 255, 255, 0.1);
  box-shadow:
      0 2px 8px rgba(0, 0, 0, 0.1),
      inset 0 1px 1px rgba(255, 255, 255, 0.1);
  position: relative;
  overflow: hidden;
}

.user-info::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(
      to right,
      rgba(255, 255, 255, 0) 0%,
      rgba(255, 255, 255, 0.05) 50%,
      rgba(255, 255, 255, 0) 100%
  );
  transform: translateX(-100%);
  transition: transform 0.6s ease;
}
.user-info:hover {
  background: rgba(255, 255, 255, 0.15);
  transform: translateY(-2px);
  box-shadow:
      0 4px 16px rgba(0, 0, 0, 0.12),
      inset 0 1px 1px rgba(255, 255, 255, 0.15);
}

.user-info:hover::before {
  transform: translateX(100%);
}
.username {
  font-size: 28px;
  font-weight: 500;
  letter-spacing: 0.3px;
}

/* 左侧菜单样式 */
.main-container {
  display: flex;
  margin-top: 64px;
  min-height: calc(100vh - 64px);
}

.aside {
  background: #ffffff;
  border-right: 1px solid #e6e9f0;
  transition: width 0.3s ease;
  position: fixed;
  top: 80px;
  bottom: 0;
  left: 0;
  z-index: 999;
  box-shadow: 4px 0 20px rgba(0, 0, 0, 0.04);
}

.menu-header {
  height: 91px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-bottom: 1px solid #e6e9f0;
  background: #fafbfc;
}

.collapse-btn {
  font-size: 20px;
  color: #606266;
  transition: all 0.3s ease;
}

.collapse-btn:hover {
  color: #165DFF;
  transform: rotate(180deg);
}

/* 自定义菜单样式 */
:deep(.el-menu) {
  background: transparent;
  border-right: none;
}

:deep(.el-menu-item) {
  height: 54px;
  line-height: 54px;
  font-size: 20px; /* 原始字体大小从16px调大到18px */
  color: #606266; /* 原始文字颜色 */
  transition: all 0.3s ease;
  position: relative;
  padding-left: 20px !important;
  margin: 4px 0;
  border-radius: 8px;
  margin: 0 8px;
}

:deep(.el-menu-item.is-active) {
  color: #ffffff; /* 激活状态文字颜色 */
  background: #165DFF; /* 激活状态背景颜色 */
  border-right: none;
  border-left: 3px solid #165DFF;
  transform: translateX(2px);
  font-weight: 500;
}

:deep(.el-menu-item:hover) {
  background: #e6f7ff; /* 悬停状态背景颜色 */
  color: #165DFF; /* 悬停状态文字颜色 */
  transform: translateX(2px);
}

:deep(.el-menu-item .el-icon) {
  font-size: 20px;
  margin-right: 14px;
  min-width: 20px;
  transition: all 0.3s ease;
}

:deep(.el-menu-item:hover .el-icon),
:deep(.el-menu-item.is-active .el-icon) {
  color: #165DFF; /* 悬停和激活状态图标颜色 */
  transform: scale(1.15);
}

:deep(.el-menu--collapse .el-menu-item .el-icon) {
  margin-right: 0;
}

/* 主要内容区 */
.main {
  flex: 1;
  margin-left: 220px;
  padding: 32px 40px;
  transition: margin-left 0.3s ease;
  background-color: #f9fafb;
}

.main.collapsed {
  margin-left: 64px;
}

/* 下拉菜单高级样式 */
:deep(.el-dropdown-menu) {
  border-radius: 14px;
  box-shadow:
      0 12px 32px rgba(0, 0, 0, 0.16),
      0 2px 6px rgba(0, 0, 0, 0.08);
  border: none;
  transform-origin: top right;
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
  padding: 8px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 20px;
  font-size: 15px;
  transition: all 0.3s ease;
  color: #606266;
  border-radius: 8px;
  margin: 4px 0;
  position: relative;
  overflow: hidden;
}

:deep(.el-dropdown-menu__item::before) {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 3px;
  height: 100%;
  background: #165DFF;
  transform: translateX(-10px);
  transition: transform 0.3s ease;
}

:deep(.el-dropdown-menu__item:hover) {
  background-color: rgba(22, 93, 255, 0.08);
  transform: translateX(4px);
  color: #165DFF;
}

:deep(.el-dropdown-menu__item:hover::before) {
  transform: translateX(0);
}

:deep(.el-dropdown-menu__item .el-icon) {
  margin-right: 0;
  color: #909399;
  font-size: 16px;
  transition: all 0.3s ease;
}

:deep(.el-dropdown-menu__item:hover .el-icon) {
  color: #165DFF;
  transform: scale(1.1);
}

:deep(.el-dropdown-menu__item.divided) {
  border-top: 1px solid rgba(0, 0, 0, 0.05);
  position: relative;
}

:deep(.el-dropdown-menu__item.divided::before) {
  content: '';
  position: absolute;
  top: -1px;
  left: 20px;
  right: 20px;
  height: 1px;
  background: rgba(255, 255, 255, 0.1);
}
/* 路由切换动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 新增二级菜单样式 */
:deep(.el-sub-menu__title) {
  height: 54px;
  line-height: 54px;
  font-size: 20px;
  color: #606266;
  transition: all 0.3s ease;
}

:deep(.el-sub-menu__title:hover) {
  background: #e6f7ff;
  color: #165DFF;
  transform: translateX(2px);
}

:deep(.el-sub-menu__title .el-icon) {
  font-size: 20px;
  margin-right: 14px;
  min-width: 20px;
  transition: all 0.3s ease;
}

:deep(.el-sub-menu__title:hover .el-icon) {
  color: #165DFF;
  transform: scale(1.15);
}

:deep(.el-menu--collapse .el-sub-menu__title .el-icon) {
  margin-right: 0;
}

:deep(.el-menu-item.is-active) {
  color: #ffffff;
  background: #165DFF;
  border-right: none;
  border-left: 3px solid #165DFF;
  transform: translateX(2px);
  font-weight: 500;
}


/* 更现代的圆角间距样式 - 调整上下间距 */
:deep(.el-menu-item),
:deep(.el-sub-menu__title) {
  margin: 30px 10px; /* 上下从4px调整为8px，左右保持8px */
  border-radius: 6px;
  transition: all 0.3s ease;
}

/* 悬停状态调整 */
:deep(.el-menu-item:hover),
:deep(.el-sub-menu__title:hover) {
  margin: 10px 6px;  /* 悬停时上下10px(增加2px)，左右6px */
}

/* 二级菜单单独调整 */
:deep(.el-sub-menu .el-menu-item) {
  margin: 19px 8px;   /* 二级菜单上下6px */
  height: 40px;      /* 高度适当减小 */
  line-height: 40px; /* 行高匹配 */
}

/* 激活状态保持突出 */
:deep(.el-menu-item.is-active) {
  margin: 8px 8px;   /* 与普通状态一致 */
  box-shadow: 0 2px 8px rgba(22, 93, 255, 0.2); /* 增加阴影突出 */
}

.avatar-uploader .el-avatar {
  border: 2px solid #fff;
  transition: box-shadow 0.3s;
}
.avatar-uploader:hover .el-avatar {
  box-shadow: 0 0 8px #165DFF;
}

/* 个人信息对话框样式 */
.profile-dialog :deep(.el-dialog) {
  border-radius: 16px;
  overflow: hidden;
}

.profile-dialog :deep(.el-dialog__header) {
  background: linear-gradient(135deg, #165DFF 0%, #4096FF 100%);
  color: white;
  padding: 20px 24px;
  margin: 0;
}

.profile-dialog :deep(.el-dialog__title) {
  color: white;
  font-size: 18px;
  font-weight: 600;
}

.profile-dialog :deep(.el-dialog__headerbtn .el-dialog__close) {
  color: white;
  font-size: 20px;
}

.profile-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.profile-content {
  padding: 24px;
}

.avatar-section {
  text-align: center;
  margin-bottom: 24px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 12px;
}

.profile-avatar-uploader {
  display: inline-block;
}

.profile-avatar-uploader .el-avatar {
  border: 4px solid #fff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.profile-avatar-uploader:hover .el-avatar {
  transform: scale(1.05);
  box-shadow: 0 6px 20px rgba(22, 93, 255, 0.2);
}

.upload-hint {
  margin-top: 8px;
  font-size: 14px;
  color: #909399;
}

.profile-form {
  margin-top: 20px;
}

.profile-form :deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

.profile-form :deep(.el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 0 0 1px #dcdfe6 inset;
  transition: all 0.3s ease;
}

.profile-form :deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #165DFF inset;
}

.profile-form :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #165DFF inset;
}

.profile-form :deep(.el-textarea__inner) {
  border-radius: 8px;
  box-shadow: 0 0 0 1px #dcdfe6 inset;
  transition: all 0.3s ease;
}

.profile-form :deep(.el-textarea__inner:hover) {
  box-shadow: 0 0 0 1px #165DFF inset;
}

.profile-form :deep(.el-textarea__inner:focus) {
  box-shadow: 0 0 0 1px #165DFF inset;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 24px;
  background: #f8f9fa;
  border-top: 1px solid #e9ecef;
}

.dialog-footer .el-button {
  border-radius: 8px;
  padding: 10px 20px;
  font-weight: 500;
}
</style>